package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 * HTTP协议要求一问一答
 * 对此,这里的处理大致分为三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);
            //2处理请求
            String path = request.getUri();
            System.out.println("抽象路径:" + path);
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(baseDir, "static");
            File file = new File(staticDir, path);

            /*
                V6新增内容:
                添加一个分支判断,file对象是否表示的是一个文件, 如果是则将该文件响应给
                浏览器.如果不是应当响应404页面给浏览器
             */
           //状态描述
            /*封装到响应对象中*/
            if (file.isFile()) {
                response.setContentFile(file);
            } else {
                file = new File(staticDir, "404.html");
                response.setStatusCode(400);
                response.setStatusReason("Not Found");
                response.setContentFile(file);
            }

            //3.3发送响应正文
/*v8中由于发送响应的操作移动到response的方法中,因此这里改用调方法*/
            response.response();



        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向客户端发送一行字符串
     */



}
